import {reqCartList,reqDeleteCartById,reqUpdateCheckedByid} from '@/api';
const state = {
    cartList:[],
};
const mutations = {
    GETCARTLIST(state,cartList) {
        state.cartList = cartList
    }
};
const actions = {
    //获取购物车列表数据
    async getCartList({commit}){
        let result = await reqCartList();
        //console.log(result);
        if(result.code == 200){
            commit("GETCARTLIST",result.data)
        }
    },

    //删除购物车某一个产品
    // eslint-disable-next-line no-unused-vars
    async deleteCartListBySkuId({commit},skuId){
        let result = await reqDeleteCartById(skuId);
        if(result.code == 200){
           return '删除成功'
        }else{
           return Promise.reject(new Error('fail'));
        }
    },
     //修改购物车某一个产品的选中状态
  // eslint-disable-next-line no-unused-vars
  async updateCheckedById({ commit }, { skuId, isChecked }) {
    let result = await reqUpdateCheckedByid(skuId, isChecked);
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error("fail"));
    }
  },
  //删除选中的产品
  deleteAllCheckedCart({dispatch,getters}){

    let PromiseAll = [];
   getters.cartList.cartInfoList.forEach((item) => { 
    let promise = item.isChecked == 1
        ? dispatch("deleteCartListBySkuId",item.skuId)
        : "";
        //将每次返回的promise添加到数组当中
        PromiseAll.push(promise)
    });
    //要保证每次的promise(简称p),p拿到成功的值,使用promise的方法all
    //如果有一个失败返回即为失败结果
    return Promise.all(PromiseAll);
},
 //修改全部产品的状态
 updateAllCartIsChecked({ dispatch, state }, isChecked) {
    //数组
    let promiseAll = [];
    state.cartList[0].cartInfoList.forEach((item) => {
      let promise = dispatch("updateCheckedById", {
        skuId: item.skuId,
        isChecked,
      });
      promiseAll.push(promise);
    });
    //最终返回结果
    return Promise.all(promiseAll);
  },
};
const getters = {
    cartList(state){
        return state.cartList[0] || {}
    }
};
export default {
    namespaced:true,
    state,
    mutations,
    actions,
    getters,
}